package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtProperties jwtProperties;
    public static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        // 1. 发送请求到微信接口中，获取openid
        Map<String, String> params = new HashMap<>();
        params.put("appid", weChatProperties.getAppid());
        params.put("secret", weChatProperties.getSecret());
        params.put("js_code", userLoginDTO.getCode());
        params.put("grant_type", "authorization_code");
        String jsonStr = HttpClientUtil.doGet(WX_LOGIN_URL, params);
        // 从结果的json中获取openid
        String openid = JSON.parseObject(jsonStr).getString("openid");
        log.info("微信登录成功，获取的openid：{}", openid);
        // 2. 根据openid构建用户信息，往我们的用户表中进行存储（前提是用户之前没有登陆过）
        // 使用openid为条件到数据库查询用户信息
        User user = userMapper.findByOpenid(openid);
        if (user == null) {
            // 如果查询不到，需要新增用户
            user = User.builder().openid(openid).createTime(LocalDateTime.now()).build();
            // 保存到数据库
            userMapper.insert(user);
        }
        // 3. 生成令牌，返回结果
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        UserLoginVO vo = UserLoginVO.builder()
                .id(user.getId())
                .token(token)
                .openid(openid)
                .build();

        return vo;
    }
}
